//
//  JMConcernSchoolViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/2.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMConcernSchoolViewController.h"
#import "JMAcademyCell.h"
#import "JMconcernSchoolViewMode.h"
#import "JMCollegesMode.h"
#import "JMAcademInfoViewController.h"
#import "JMLoginViewController.h"


@interface JMConcernSchoolViewController ()<UITableViewDelegate,UITableViewDataSource>
{

    int lastId;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation JMConcernSchoolViewController


- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataArray;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationItem.title = @"我关注的学校";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self setupRefresh];
}
#pragma mark 上下拉刷新数据
- (void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}
-(void)headerRereshing{
    lastId = 0;
    [self getMessageFromeServer];
}
-(void)footerRereshing{
    [self getMessageFromeServer];
}

-(void)getMessageFromeServer{
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:@"0"forKey:@"last"];
        [dict setObject:@"15"forKey:@"size"];
        [JMconcernSchoolViewMode fetchConcerSchoolMessageParametes:dict block:^(id data, NSError *error, id currData) {
            [JMTools hiddenAlerView:self.view];
            if([[data objectForKey:@"status"] integerValue] == 1){
                [JMTools showAlertView:self.view message:data[@"message"]];
                if(lastId == 0)[self.dataArray removeAllObjects];
                NSArray *array = (NSArray *)currData;
                if(lastId == [[currData lastObject] collegeId]){
                    [JMTools showAlertView:self.view message:@"没有更多数据"];
                }else{
                    [self.dataArray addObjectsFromArray:array];
                    lastId = [[currData lastObject] collegeId];
                    [self.tableView reloadData];
                }
                
            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
                JMLoginViewController *vc =[JMLoginViewController new];
                JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:vc];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        }];
    }

}

#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * str=@"ID";
    JMAcademyCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMAcademyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
    JMCollegesMode *mode = self.dataArray[indexPath.row];
    [cell upCellInfoWith:mode];
    [cell.attentionBtn addTarget:self action:@selector(attentionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionBtn.tag = indexPath.row;
    if([mode.attention isEqualToString:@"1"]){
        cell.attentionBtn.type = @"1";
        [cell.attentionBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
    }else{
        cell.attentionBtn.type = @"0";
        [cell.attentionBtn setTitle:@"关注" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JMAcademInfoViewController *vc = [JMAcademInfoViewController  new];
    vc.mode =self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return UI_SCREEN_WITH *0.234375;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(void)attentionButtonClick:(JMAttenButton *)sender{
    JMCollegesMode *mode = [self.dataArray objectAtIndex:sender.tag];
    
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if([sender.type isEqualToString:@"0"]){
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient addSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"取消" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
                    [JMTools showAlertView:self.view message:data[@"message"]];
                    sender.type =@"1";
                    mode.attention = @"1";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];

                    [JMTools showAlertView:self.view message:data[@"message"]];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];
            }];
        }
    }else{
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient cancleSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"关注" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
                    sender.type =@"0";
                    mode.attention = @"0";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];

                    [JMTools showAlertView:self.view message:data[@"message"]];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];
                
            }];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
